package com.waste.game.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisUtil {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private RedisConnectionFactory connectionFactory;
    /**
     * 自增序列（有过期时间）
     * @param key 自增key
     * @param liveTime 存活时间(秒)
     * @return
     */
    public Long incr(String key, long liveTime) {
        if (null == connectionFactory) {
            connectionFactory = redisTemplate.getConnectionFactory();
        }
        assert connectionFactory != null;
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, connectionFactory);
        long increment = entityIdCounter.getAndIncrement();
        if (increment == 0 && liveTime > 0) {
            //初始设置过期时间
            entityIdCounter.expire(liveTime, TimeUnit.SECONDS);
        }
        return increment;
    }

    /**
     * 自增序列（可设置初始值）
     * @param key 自增key
     * @param value 初始值
     * @description 若自增key已存在，并且初始值必须要大于生成的值，以免造成序列冲突
     * @return
     */
    public void setIncr(String key, int value) {
        if (value < 0) {
            value = 1;
        }
        if (null == connectionFactory) {
            connectionFactory = redisTemplate.getConnectionFactory();
        }
        assert connectionFactory != null;
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, connectionFactory);
        entityIdCounter.set(1);
    }

    public Long getIncr(String key) {
        if (null == connectionFactory) {
            connectionFactory = redisTemplate.getConnectionFactory();
        }
        assert connectionFactory != null;
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, connectionFactory);
        return entityIdCounter.getAndIncrement();
    }
}
